import Koa from 'koa'
import KoaBody from 'koa-body'
import parameter from 'koa-parameter'  // 使用koa-parameter校验参数
import session from 'koa-session'
import cors from 'koa2-cors'
import KoaStatic from 'koa-static'
import path from 'path'
import router from '../router/index.js'
import errHandler from './errHandler.js'
import ctxfun from './ctxfun.js'
import { __dirname } from "../utils/common.js"

const app = new Koa()

for (let item of Object.keys(ctxfun)) {
  app.use(ctxfun[item])
}

// 解决跨域问题
app.use(
  cors({
    // 如果前端配置了withCredentials=true，后端设置Access- Control - Allow - Origin不能为 " * ", 而必须是你的源地址。
    origin: (ctx) => { // 设置允许来自指定域名请求
      console.log("url: " + ctx.url)
      if (ctx.url.includes('/dev')) {
        return 'http://localhost:8081' // 只允许此域名的请求
      }
    },
    maxAge: 5, // 指定本次预检请求的有效期，单位为秒。
    credentials: true, // 是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 设置服务器支持的所有头信息字段
  })
)

app.keys = [process.env.SESSION_SECREAT]	// session加密字段
const CONFIG = {
  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  // secure: true, /** (boolean) secure cookie*/
  sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
}
app.use(session(CONFIG, app))

app.use(KoaBody({
  multipart: true,
}))
app.use(parameter(app))
app.use(router.routes())
// app.use('/', router)
app.use(router.allowedMethods());
app.use(KoaStatic(path.join(__dirname(import.meta.url), '../static')))

// 捕捉错误
app.on('error', errHandler)

export default app